package com.budwk.app.sqfwV2.service.caringStaff;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.dto.PartyMemberInformation;
import com.budwk.app.sqfw.dto.PersonnelTagDTO;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.models.Sqfw_form_summary_pdf;
import com.budwk.app.sqfw.services.PartyMemberInformationService;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryPdfService;
import com.budwk.app.sqfw.services.SqfwServicerecordService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowBusinessParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CompleteFlowPdfParamForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfPdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService.CompleteFlowCommonPdfService;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sqfwV2.dto.CaringStaffDTO;
import com.budwk.app.sqfwV2.dto.dto.AuthenticRightDTO;
import com.budwk.app.sqfwV2.enums.CaringStaffEnum;
import com.budwk.app.sqfwV2.generator.caringStaff.CaringStaffPdfGenerator;
import com.budwk.app.util.poiUtils.CommonPdfAndWordResult;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.io.ByteArrayOutputStream;
import java.util.*;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.word2PdfAndUpload;

@IocBean
public class CaringStaffPdfService extends CompleteFlowCommonPdfService {
    @Inject
    SqfwServicerecordService sqfwServicerecordService;
    @Inject
    SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SqfwFormSummaryPdfService formSummaryPdfService;

    @Inject
    private PartyMemberInformationService partyMemberInformationService;

    @Override
    public void createPdfAndMsg(CompleteFlowPdfParamForController paramForController) {
        super.createPdfAndMsg(paramForController);
    }


    @Override
    public GeneratorPdfWordResult createPdfSync(CompleteFlowPdfParamForController paramForController) {
        return super.createPdfSync(paramForController);
    }

    /**
     * 获取用户自定义字段 代码生成器已经自动填充
     * 无需特殊修改
     *
     * @param paramData json字符串
     * @return 结果
     */
    @Override
    protected AbstractCustomerPdfCreateField getCustomerPdfField(String paramData) {
        return JSONObject.parseObject(paramData, CaringStaffDTO.class);
    }

    /**
     * 允许用户自定义填充在创建pdf时所提供的数据
     *
     * @param pdfGenerateParam 创建pdf所提供的数据
     */
    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {


    }

    /**
     * 在这里设置生成pdf的所有generator
     *
     * @param pdfGenerateParam 创建pdf的参数
     * @return 生成pdf的generator合集
     */
    @Override
    protected List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam) {
        List<BasePdfGenerator> generatorList = Lists.newArrayList();
        CompleteFlowBusinessParam businessParam = (CompleteFlowBusinessParam) pdfGenerateParam.getBusinessParam();
        Sqfw_formSummary_new formSummary = businessParam.getFormSummary();
        CaringStaffDTO CaringStaffDTO = JSON.parseObject(formSummary.getParamData(), CaringStaffDTO.class);
        List<String> typeList = Arrays.asList(CaringStaffDTO.getType().split(","));
        for (String s : typeList) {
            CaringStaffPdfGenerator caringStaffPdfGenerator = null;
            if (s.equals("定期访视")) {
                if (CaringStaffDTO.getCareCategory().contains("空巢老人") || CaringStaffDTO.getCareCategory().contains("独居老人")) {
                    caringStaffPdfGenerator = new CaringStaffPdfGenerator(CaringStaffEnum.D.getTemplat());
                } else {
                    caringStaffPdfGenerator = new CaringStaffPdfGenerator(CaringStaffEnum.B.getTemplat());
                }
            } else {
                caringStaffPdfGenerator = new CaringStaffPdfGenerator(CaringStaffEnum.A.getTemplat());
            }
            caringStaffPdfGenerator.setDownName(CaringStaffEnum.getFileName(s));
            Sqfw_form_summary_pdf sqfwFormSummaryPdf = new Sqfw_form_summary_pdf();
            sqfwFormSummaryPdf.setSummaryId(formSummary.getId());
            sqfwFormSummaryPdf.setIndex(CaringStaffEnum.getCode(s));
            caringStaffPdfGenerator.setSqfwFormSummaryPdf(sqfwFormSummaryPdf);
            generatorList.add(caringStaffPdfGenerator);
        }
        return generatorList;
    }

    /**
     * 用户自定义下载pdf文件的名称
     *
     * @param pdfGenerateParam 创建pdf所提供的参数
     * @return 结果
     */
    @Override
    protected String getDownloadFileName(PdfGenerateParam pdfGenerateParam) {
        CompleteFlowBusinessParam businessParam = (CompleteFlowBusinessParam) pdfGenerateParam.getBusinessParam();
        Sqfw_formSummary_new formSummary = businessParam.getFormSummary();
        CaringStaffDTO CaringStaffDTO = JSON.parseObject(formSummary.getParamData(), CaringStaffDTO.class);
        return StrUtil.format("{}关爱人员探访记录表", CaringStaffDTO.getName());
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    public String getSummaryType() {
        return SqfwFormSummaryConstants.CARE_WORKER_VISIT;
    }

    /**
     * 允许可以在统一处理结果
     *
     * @param pdfResult pdf结果
     */
    protected void getPdfGenerateResultAfter(ResultOfPdfGenerator pdfResult, BasePdfGenerator generator) {
        List<ByteArrayOutputStream> outputStreamList = new ArrayList<>();
        outputStreamList.add(pdfResult.getPdfOS());
        CaringStaffPdfGenerator pdfGenerator = (CaringStaffPdfGenerator) generator;
        CommonPdfAndWordResult wordPdfResult = word2PdfAndUpload(outputStreamList, pdfGenerator.getDownName(), "");
        Sqfw_form_summary_pdf sqfwFormSummaryPdf = pdfGenerator.getSqfwFormSummaryPdf();
        if (StringUtils.isNotBlank(wordPdfResult.getPdfUrl())) {
            sqfwFormSummaryPdf.setUrl(wordPdfResult.getPdfUrl());
            sqfwFormSummaryPdf.setStatus("2");
        } else {
            sqfwFormSummaryPdf.setStatus("1");

        }
        sqfwFormSummaryPdf.setCreateDate(new Date());
        Sqfw_form_summary_pdf updateDto = formSummaryPdfService.fetch(Cnd.where(Sqfw_form_summary_pdf::getSummaryId, "=", sqfwFormSummaryPdf.getSummaryId())
                .and(Sqfw_form_summary_pdf::getIndex, "=", sqfwFormSummaryPdf.getIndex()));
        if (ObjectUtil.isEmpty(updateDto)) {
            formSummaryPdfService.insert(sqfwFormSummaryPdf);
        } else {
            updateDto.setUrl(sqfwFormSummaryPdf.getUrl());
            formSummaryPdfService.update(updateDto);
        }
    }
    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {
        CaringStaffDTO caringStaffDTO = JSON.parseObject(formSummary.getParamData(), CaringStaffDTO.class);
        PartyMemberInformation partyMemberInformation=null;
        if(StrUtil.isNotEmpty(caringStaffDTO.getId())){
            partyMemberInformation = partyMemberInformationService.fetch(caringStaffDTO.getId());
        }else {
            partyMemberInformation = partyMemberInformationService.fetch(Cnd.where("id_number", "=", caringStaffDTO.getIDNumber())
                    .and(PartyMemberInformation::getName, "=", caringStaffDTO.getName())
                    .and(PartyMemberInformation::getCounty, "=", formSummary.getCounty())
                    .and(PartyMemberInformation::getCommunity, "=", formSummary.getCommunity())
                    .and(PartyMemberInformation::getDistrict, "=", formSummary.getDistrict()));
        }
        if (ObjectUtil.isEmpty(partyMemberInformation)) {
            partyMemberInformation = new PartyMemberInformation();
            BeanUtil.copyProperties(caringStaffDTO, partyMemberInformation,"id");
            BeanUtil.copyProperties(formSummary, partyMemberInformation,"id");
            partyMemberInformation.setIdNumber(caringStaffDTO.getIDNumber());
            partyMemberInformation.setBusinessType(SqfwFormSummaryConstants.CARE_WORKER_VISIT);
            partyMemberInformation.setSummaryId(formSummary.getId());
            partyMemberInformation.setSpecialMark("["+caringStaffDTO.getPersonnelTag()+"]");
            partyMemberInformationService.insert(partyMemberInformation);
        }else {
            BeanUtil.copyProperties(caringStaffDTO, partyMemberInformation,"id","businessType");
            partyMemberInformation.setIdNumber(caringStaffDTO.getIDNumber());
            if(StrUtil.isEmpty(partyMemberInformation.getBusinessType())){
                partyMemberInformation.setBusinessType(SqfwFormSummaryConstants.CARE_WORKER_VISIT);
            }else{
                if(!partyMemberInformation.getBusinessType().contains(SqfwFormSummaryConstants.CARE_WORKER_VISIT)){
                    partyMemberInformation.setBusinessType(partyMemberInformation.getBusinessType()+","+SqfwFormSummaryConstants.CARE_WORKER_VISIT);
                }
            }
            BeanUtil.copyProperties(formSummary, partyMemberInformation,"id");
            partyMemberInformation.setSpecialMark(getlist(partyMemberInformation.getSpecialMark(),  caringStaffDTO.getPersonnelTag()));
            partyMemberInformation.setSummaryId(formSummary.getId());
            partyMemberInformationService.update(partyMemberInformation);
        }
        caringStaffDTO.setId(partyMemberInformation.getId());
        formSummary.setParamData(JSON.toJSONString(caringStaffDTO));
    }

    private String getlist( String specialMark ,String personnelTag){
        PersonnelTagDTO tagDTO = JSONUtil.toBean(personnelTag,PersonnelTagDTO.class);
        List<PersonnelTagDTO>  list = new ArrayList<>();
        if(StrUtil.isNotEmpty(specialMark)){
            list= JSONUtil.toList(specialMark,PersonnelTagDTO.class);
            Optional<PersonnelTagDTO> first =  list.stream().filter(s->s.getBusinessType().equals(SqfwFormSummaryConstants.CARE_WORKER_VISIT)).findFirst();
            if(first.isPresent()){
                for (PersonnelTagDTO personnelTagDTO : list) {
                    if(personnelTagDTO.getBusinessType().equals(SqfwFormSummaryConstants.CARE_WORKER_VISIT)){
                        personnelTagDTO.setTag(tagDTO.getTag());
                    }
                }
            }else {
                list.add(tagDTO);
            }
        }else {
            list.add(tagDTO);
        }
        specialMark = JSONUtil.toJsonStr(list);
        return specialMark;
    }
    protected void afterInsertForSummary(Sqfw_formSummary_new formSummary) {
        sqfwServicerecordService.afterInsertForSummary(formSummary);
    }


}

